import * as http from 'http';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as path from 'path';
import * as compression from 'compression';
import session = require('express-session');
import cookieParser = require('cookie-parser');
import ejs = require('ejs');

import {MysqlClient} from './dao/index';
import {EnvUtils} from './utils/EnvUtils';

import * as JwtToken from 'jsonwebtoken';

let env = require("./env.json");

var app = express();
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);
app.set('views', __dirname + '/views');
export function init(port: number, mode: string) {

    EnvUtils.init(env[mode],mode);
    //连接数据库
    MysqlClient.init();

    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());
    app.use(bodyParser.text());
    app.use(compression());
    app.use(cookieParser());
    /**
     *
     * Dev Mode.
     * @note Dev server will only give for you middleware.
     */
    if (mode == 'dev') {
        let root = path.resolve(process.cwd());
        let clientRoot = path.resolve(__dirname, 'public');
        app.use(express.static(root));
        app.use(express.static(__dirname));
        app.use(express.static(clientRoot));
        app.use(express.static(path.resolve(root, 'node_modules')));

        //初始化路由
        let routes = require('./routes');
        routes.init(app);


    } else {
        let root = path.resolve(process.cwd());
        let distProd = path.resolve(root,"dist/prod/public");

        app.use(express.static(distProd));
        app.use(express.static(root));
        app.use(express.static(path.resolve(root, 'node_modules')));

        //初始化路由
        let routes = require('./routes');
        routes.init(app);
    }

    app.use(function(req, res, next){
        res.redirect('/404.html');
    });

    /**
     * Server with gzip compression.
     */
    return new Promise<http.Server>((resolve, reject) => {
        let server = app.listen(port, () => {
            var port = server.address().port;
            console.log('App is listening on port:' + port);
            resolve(server);
        });
    });
};


process.on('uncaughtException', function (err:any) {
    //打印出错误
    console.log(err);
    //打印出错误的调用栈方便调试
    console.log(err.stack);
});
